package com.cynen.p42u.task;

import com.cynen.p42u.pojo.JavLibInfo;
import com.cynen.p42u.service.JavLibService;
import com.cynen.p42u.util.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 此模块主要是多开一个任务,进行后台下载图片.
 * 只需要传入图片的url即可.
 */
@Component
public class DownloadPic {

    @Autowired
    private JavLibService javLibService;

    @Autowired
    private HttpUtils httpUtils;

    // 初始化查询的页码 [数据库的页码]
    private int currPage = 0;

    /**
     *initialDelay 应用启动后,1秒后启动任务.
     * fixedDelay : 上一次任务完成后,等待此设定时间,再次启动任务.
     */
    @Scheduled(initialDelay = 200*1000,fixedDelay = 300*1000)
    public void getPic(){
        System.out.println("图片下载开始....");
        // List<JavLibInfo> list = javLibService.findAl();

        // 只查询未下载的.
        // JavLibInfo info = new JavLibInfo();
        // info.setDownloads(0);
        //List<JavLibInfo> list = javLibService.findAll(info);

        Page page = javLibService.findPage(currPage,1000); // 如果只查询未下载的,不用增加页码.
        System.out.println("当前查询页: "+(currPage+1)+",当前pageSize=200");
        if (page.getContent().size() == 1000){
            // 只有当前是1000条记录时,才加1
            currPage ++;
        }
        if (page.getContent().size() == 0){
            // 爬完了...
            return ;
        }

        List<JavLibInfo> list = page.getContent();
        if (list.size() > 0){
            for(JavLibInfo javLibInfo:list){
                if(javLibInfo.getDownloads() == 0 ){
                    httpUtils.doGetImage(javLibInfo);
                }else {
                    System.out.println(javLibInfo.getVideoId() + "已下载");
                }
            }
        }
    }
}
